﻿using Newtonsoft.Json;

namespace Infrastructure.Model
{
    /// <summary>
    /// Api相应结果
    /// </summary>
    public class ApiResult
    {
        public int Code { get; set; }

        public string Msg { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public object Data { get; set; }

        [JsonIgnore]
        public bool IsSuccess => Code == 200;

        public ApiResult()
        {
        }

        public ApiResult(int code, string msg)
        {
            Code = code;
            Msg = msg;
        }

        public ApiResult(int code, string msg, object data)
        {
            Code = code;
            Msg = msg;
            if (data != null)
            {
                Data = data;
            }
        }

        public ApiResult Success()
        {
            Code = 200;
            Msg = "success";
            return this;
        }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }

        public static ApiResult Success(object data)
        {
            return new ApiResult(HttpStatus.SUCCESS, "success", data);
        }

        public static ApiResult Success(string msg)
        {
            return new ApiResult(HttpStatus.SUCCESS, msg, null);
        }

        public static ApiResult Success(string msg, object data)
        {
            return new ApiResult(HttpStatus.SUCCESS, msg, data);
        }

        public ApiResult On401()
        {
            Code = 401;
            Msg = "access denied";
            return this;
        }

        public ApiResult Error(ResultCode resultCode, string msg = "")
        {
            Code = (int)resultCode;
            Msg = msg;
            return this;
        }

        public static ApiResult Error(int code, string msg)
        {
            return new ApiResult(code, msg);
        }

        public static ApiResult Error(string msg)
        {
            return new ApiResult(400, msg);
        }
    }



    public class ApiResult<T> : ApiResult where T : class
    {
        public T Item { get; set; }

        public ApiResult(int code, string msg, T item)
            : base(code, msg, item)
        {
            Item = item;
        }

        public static ApiResult<T> Success(T item)
        {
            return new ApiResult<T>(HttpStatus.SUCCESS, "", item);
        }

        public static ApiResult<T> Success(string msg, T item)
        {
            return new ApiResult<T>(HttpStatus.SUCCESS, msg, item);
        }

        public new static ApiResult<T> Error(string msg)
        {
            return new ApiResult<T>(HttpStatus.BAD_REQUEST, msg, null);
        }
    }
}
